package org.example.kafka.selfpartition;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.serialization.StringSerializer;
import org.example.kafka.common.CommonConstant;
import org.example.kafka.common.KafkaConstants;

import java.util.Properties;
import java.util.concurrent.Future;

/**
 * 可以和KafkaFutureProducer比较分区结果
 */
public class SelfPartitionProducer {
    private static KafkaProducer<String,String> producer = null;

    public static void main(String[] args) {
        /*消息生产者*/
        Properties properties
                = KafkaConstants.producerConfig(StringSerializer.class,
                StringSerializer.class);
        //使用自定义的分区器
        properties.put(ProducerConfig.PARTITIONER_CLASS_CONFIG,
                "org.example.kafka.selfpartition.SelfPartitioner");

        producer = new KafkaProducer<String, String>(properties);
        try{
            // 待发送的消息实例
            ProducerRecord<String,String> record;
            try{
                record = new ProducerRecord<String,String>(CommonConstant.SELF_PARTITION_TOPIC,"who","rui");
                Future<RecordMetadata>future = producer.send(record);
                System.out.println("do other sth");
                RecordMetadata recordMetadata = future.get();
                if(null!=recordMetadata){
                    System.out.println(String.format("偏移量：%s,分区：%s",
                            recordMetadata.offset(),
                            recordMetadata.partition()));
                }
            }catch (Exception e){
             e.printStackTrace();
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            producer.close();
        }

    }
}
